//
//  MSLGreetCardController.m
//  ExtModule
//
//  Created by CPX on 2018/6/29.
//  Copyright © 2018年 CPX. All rights reserved.
//

#import "MSLGreetCardController.h"
#import "MSLFontListView.h"
#import "MSLColorListView.h"
#import "MSLAlignemntView.h"
#import "GreetConfigView.h"
#import "UIColor+YYAdd.h"
#import "UIImage+Additions.h"

/**
 贺卡编辑页面
 author:王连友
 */
@interface MSLGreetCardController ()<UIGestureRecognizerDelegate>

@property (nonatomic,strong)GreetConfigView *bottomView;
@property (nonatomic,strong)UIImageView * imagView_bg;//背景图
@property (nonatomic,strong)UIImageView * imagView_text;//小图

@property (nonatomic,strong)NSArray *containerArray;
@property (nonatomic,strong)UILabel * textLabel;//贺卡文本


@property (nonatomic,strong)UIImage * image_bg_origin;//原始文字图、用于添加阴影等

@end

@implementation MSLGreetCardController

//必须在视图展示完成设置拖动。因为拖动会清楚所有约束
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    
}
#pragma mark ------界面构造
-(void)initViews{
    WeakSelf;
// 底部几个功能按钮 view
    self.bottomView = [[GreetConfigView alloc] initWithFrame:CGRectMake(0, kScreenHeight - 50, kScreenWidth, 50)
                                                     titles:@[@"",@"",@""] normalImage:@[[UIImage imageNamed:@"fonts_ic"],[UIImage imageNamed:@"color_ic"],[UIImage imageNamed:@"arrangement_ic"]] selectImages:@[[UIImage imageNamed:@"fonts_ic_s"],[UIImage imageNamed:@"color_ic_s"],[UIImage imageNamed:@"arrangement_ic_s"]]];
    [self.view addSubview:self.bottomView];
    self.bottomView.selectIndex = 0;
    self.bottomView.touchIndexEvent = ^(NSInteger index) {
        switch (index) {
            case 0:
                {
                    [weakSelf logEvent:@"gc_click_images_font"];
                    break;
                }
                case 1:
            {
                [weakSelf logEvent:@"gc_click_colorset"];
                break;
            }
            case 2:{
                [weakSelf logEvent:@"gc_click_typesettingset"];
                break;
            }
            default:
                break;
        }
        
        [weakSelf.containerArray enumerateObjectsUsingBlock:^(UIView *  obj, NSUInteger idx, BOOL * _Nonnull stop) {
            obj.hidden =  idx != index;
        }];
        
    };
    [self.bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.leading.trailing.equalTo(self.view);
        make.height.mas_equalTo(50);
    }];
    
    UIView * view = [UIView new];
    view.clipsToBounds = NO;
    view.tag = 100;
    view.layer.cornerRadius = 3;
    view.layer.masksToBounds = YES;
    view.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:view];
    [view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.mas_equalTo(NavHeight + 8);
        make.leading.equalTo(self.view.mas_leading).offset(12);
        make.centerX.equalTo(self.view);
        make.height.equalTo(view.mas_width).multipliedBy(0.75);
    }];

    self.imagView_bg = [UIImageView new];
    [view addSubview:self.imagView_bg];
    [self.imagView_bg sd_setImageWithURL:[NSURL URLWithString:self.image_model.picture] placeholderImage:[UIImage imageNamed:@"place_holder400x400"]];
    [self.imagView_bg mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(view);
        
    }];
 
    
    self.imagView_text = [UIImageView new];
    self.imagView_text.contentMode = UIViewContentModeScaleAspectFit;
    self.imagView_text.image = [UIImage imageNamed:@"place_holder200x200"];
    if (self.text_model.clifford_text_img){
        
        [self.imagView_text sd_setImageWithURL:[NSURL URLWithString:self.text_model.clifford_text_img] completed:^(UIImage * _Nullable image, NSError * _Nullable error, SDImageCacheType cacheType, NSURL * _Nullable imageURL) {
            weakSelf.image_bg_origin  = image;
            if (weakSelf.image_model.text_color){
                weakSelf.imagView_text.image = [image imageWithTintColor:[UIColor colorWithHexString:weakSelf.image_model.text_color]];

            }
            
        }];
    }
    [view addSubview:self.imagView_text];

    [self.imagView_text mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(10);
        make.width.height.mas_equalTo(110);
        make.top.mas_equalTo(20);
    }];
    
    
    self.textLabel = [UILabel new];
    self.textLabel.font = [UIFont systemFontOfSize:14];
    self.textLabel.text = self.text_model.clifford_original;
    self.textLabel.numberOfLines = 2;
    if (self.image_model.text_color){
        self.textLabel.textColor = [UIColor colorWithHexString:self.image_model.text_color];
    }
    else{
        self.textLabel.textColor = [UIColor whiteColor];
    }
    
    [view addSubview:self.textLabel];
    [self.textLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.leading.mas_equalTo(10);
        make.bottom.equalTo(view.mas_bottom).offset(-20);
        
    }];
    

    MSLFontListView  * fontContainer = [[MSLFontListView alloc]init];
    self.textLabel.highlighted = NO;
    fontContainer.selectFontEvent = ^(UIFont *font,NSInteger  index) {
        [weakSelf logEvent:@"gc_click_images_fontset" params:@{@"fontid":@(index)}];
        if (font){
            weakSelf.textLabel.font = font;
        }
        [weakSelf caculateTextSize];
        fontContainer.font_current = self.textLabel.font;

    };
    [self.view addSubview:fontContainer];
    
    MSLColorListView  * colorContainer = [[MSLColorListView alloc]init];
    colorContainer.colorSelectEvent = ^(UIColor *color,NSInteger index) {
        [weakSelf logEvent:@"gc_click_colorset" params:@{@"colorid":@(index)}];
        weakSelf.textLabel.textColor = color;
        weakSelf.imagView_text.image = [weakSelf.imagView_text.image imageWithTintColor:color];
    };
    [self.view addSubview:colorContainer];
    
    MSLAlignemntView * aliContainer  = [[MSLAlignemntView alloc]init];
    aliContainer.alignEvent = ^(NSTextAlignment alignment) {
        weakSelf.textLabel.textAlignment  = alignment;
    };
    aliContainer.opactiyEvent = ^(float value_opactiy) {
        weakSelf.imagView_text.alpha   =  value_opactiy / 100;
        weakSelf.textLabel.alpha = value_opactiy / 100;
    };
    aliContainer.shadowEvent = ^(float value_shadow) {
        [weakSelf addshadoWithshadowOffset:value_shadow];
        
    };
    [self.view addSubview:aliContainer];
    
    self.containerArray =  @[fontContainer,colorContainer,aliContainer];
    
    [self.containerArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIView* container = obj;
        container.hidden = (idx != 0);
        [container mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(view.mas_bottom).offset(12);
            make.leading.equalTo(view);
            make.centerX.equalTo(view);
            make.bottom.equalTo(self.bottomView.mas_top).offset(-8);
        }];
    }];
    
    [self addImageViewGesture];

}

-(void)initNavigation{
    [self initDefaultNavigation];
    [self.myNavigationBar.backButton setTitle:TLString(@"grt_card") forState:UIControlStateNormal];
    [self.myNavigationBar.rightButton1 setTitle:TLString(@"greeting_cards_send") forState:UIControlStateNormal];
    [self.myNavigationBar.rightButton1 setTitleColor:UIColorHex(#00732F) forState:UIControlStateNormal];
    self.myNavigationBar.rightButton1.titleLabel.font = [UIFont boldSystemFontOfSize:17];
    [self.myNavigationBar.rightButton1 addTarget:self action:@selector(sendGreetCard) forControlEvents:UIControlEventTouchUpInside];
    
    
}
#pragma mark -----图片手势添加
-(void)addImageViewGesture{
    self.imagView_text.userInteractionEnabled = YES;
    UIPinchGestureRecognizer *pinchGestureRecognizer = [[UIPinchGestureRecognizer alloc] initWithTarget:self action:@selector(pinchGestureDetected:)];
    [pinchGestureRecognizer setDelegate:self];
    [self.imagView_text addGestureRecognizer:pinchGestureRecognizer];
    
    UIRotationGestureRecognizer *rotationGestureRecognizer = [[UIRotationGestureRecognizer alloc] initWithTarget:self action:@selector(rotationGestureDetected:)];
    [rotationGestureRecognizer setDelegate:self];
    [self.imagView_text addGestureRecognizer:rotationGestureRecognizer];
    
    UIPanGestureRecognizer *panGestureRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureDetected:)];
    [panGestureRecognizer setDelegate:self];
    [self.imagView_text addGestureRecognizer:panGestureRecognizer];

    UIPanGestureRecognizer *text_pan = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(panGestureDetected:)];
    text_pan.delegate = self;
    
    self.textLabel.userInteractionEnabled = YES;
    [self.textLabel addGestureRecognizer:text_pan];
    
    
}

#pragma mark ---- STSegmentViewDelegate
- (void)buttonClick:(NSInteger)index{
    
    [self.containerArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UIView* container = obj;
        container.hidden = (idx != index);
       
    }];
}

#pragma mark -------------------------计算文本框位置
-(void)caculateTextSize{
    self.textLabel.layer.anchorPoint = CGPointMake(0.5, 0.5);
    CGPoint center = self.textLabel.center;
    
    NSString * text = self.textLabel.text;
    if (!text){
        NSAttributedString * attr = self.textLabel.attributedText;
        text = attr.string;
    }
    CGSize maxSize = self.imagView_text.superview.size;
    CGSize  size  =  [self sizeWithString:text font:self.textLabel.font maxSize:maxSize];
    self.textLabel.size = size;
    self.textLabel.center = center;
    CGRect newRect = self.textLabel.frame;
    newRect.size =size;
    
    CGFloat origin_x =  self.textLabel.frame.origin.x;
    CGFloat origin_y = self.textLabel.frame.origin.y;
    CGFloat max_x = CGRectGetMaxX(self.textLabel.frame);
    CGFloat max_y = CGRectGetMaxY(self.textLabel.frame);
    //显示label区域范围
    if (origin_x<=0){
        origin_x=0;
        newRect.origin.x  = origin_x;
    }
    if (origin_y<=0){
        origin_y = 0;
        newRect.origin.y  = origin_y;
    }
    if (max_x>=maxSize.width){
        origin_x = maxSize.width - size.width;
        newRect.origin.x = origin_x;
    }
    if (max_y>=maxSize.height){
        origin_y = maxSize.height - size.height;
        newRect.origin.y = origin_y;
    }
    NSLog(@"maxSize ----- %@ newRect --- %@",NSStringFromCGSize(maxSize),NSStringFromCGRect(newRect));
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.01 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        self.textLabel.frame = newRect;

    });
  
    
}
#pragma mark ----   给图和text 添加shadow
-(void)addshadoWithshadowOffset:(float)value{
    CGSize  size  = CGSizeMake(value, value);
    NSShadow * shadow = [[NSShadow alloc]init];
    shadow.shadowBlurRadius =  3;
    shadow.shadowOffset = size;
    shadow.shadowColor = self.textLabel.textColor;
    NSAttributedString * attri = [[NSAttributedString  alloc]initWithString:self.text_model.clifford_original attributes:@{NSShadowAttributeName:shadow}];
    self.textLabel.attributedText =  attri;
    
    UIImage * image = self.image_bg_origin;
    if (image){
        UIImageView * imageView = self.imagView_text;
        imageView.layer.shadowColor = self.textLabel.textColor.CGColor;
        
        imageView.layer.shadowOffset = size;
        
        imageView.layer.shadowOpacity = 0.6;
        
        imageView.layer.shadowRadius = 1.0;
        
        imageView.clipsToBounds = NO;
    }
    
    

}

#pragma mark ----- UIGestureRecognizerDelegate
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer
{
    return NO;
}
#pragma mark ----- 缩放手势
- (void)pinchGestureDetected:(UIPinchGestureRecognizer *)recognizer
{
    UIGestureRecognizerState state = [recognizer state];
    
    if (state == UIGestureRecognizerStateBegan || state == UIGestureRecognizerStateChanged)
    {
        CGFloat scale = [recognizer scale];
//        CGRect newRect = recognizer.view.frame;
//        newRect.size.height *= scale;
//        newRect.size.width *= scale;
        [recognizer.view setTransform:CGAffineTransformScale(recognizer.view.transform, scale, scale)];
        [recognizer setScale:1.0];
    }
}
#pragma mark ----- 拖动手势
- (void)panGestureDetected:(UIPanGestureRecognizer *)recognizer
{
    UIGestureRecognizerState state = [recognizer state];
    
    if (state == UIGestureRecognizerStateBegan || state == UIGestureRecognizerStateChanged)
    {
        
        
        CGPoint translation = [recognizer translationInView:recognizer.view];
//        CGRect newRect = recognizer.view.frame;
//        newRect.origin.y +=  translation.y;
//        newRect.origin.x += translation.x;
//        recognizer.view.frame = newRect;

//        [recognizer.view setTransform:CGAffineTransformTranslate(recognizer.view.transform, translation.x, translation.y)];
//        [recognizer setTranslation:CGPointZero inView:recognizer.view];
        if (recognizer.view == self.textLabel){
            
//                    CGRect newRect = recognizer.view.frame;
//                    newRect.origin.y +=  translation.y;
//                    newRect.origin.x += translation.x;
//                    recognizer.view.frame = newRect;
            
                    [recognizer.view setTransform:CGAffineTransformTranslate(recognizer.view.transform, translation.x, translation.y)];
                    [recognizer setTranslation:CGPointZero inView:recognizer.view];

            
                    if (recognizer.view.frame.origin.x <= 0){
                        recognizer.view.mj_x = 0;
            
                    }
                    if (recognizer.view.frame.origin.y <= 0){
                        recognizer.view.mj_y = 0;
                    }
                    //限制最大位置x
                    CGFloat max_point_x = CGRectGetMaxX(recognizer.view.frame);
                    if (max_point_x >= recognizer.view.superview.bounds.size.width){
                        recognizer.view.mj_x = recognizer.view.superview.bounds.size.width -  recognizer.view.size.width;
            
                    }
                    // 限制最大位置y
                    CGFloat max_point_y = CGRectGetMaxY(recognizer.view.frame);
                    if (max_point_y >= recognizer.view.superview.bounds.size.height){
                        recognizer.view.mj_y = recognizer.view.superview.bounds.size.height -  recognizer.view.size.height;
            
                    }
            CGRect newRect = recognizer.view.frame;
            recognizer.view.frame = newRect;
        }
        else{
            [recognizer.view setTransform:CGAffineTransformTranslate(recognizer.view.transform, translation.x, translation.y)];
            [recognizer setTranslation:CGPointZero inView:recognizer.view];
        }

        
    }
}
#pragma mark ----- 旋转手势
- (void)rotationGestureDetected:(UIRotationGestureRecognizer *)recognizer
{
    UIGestureRecognizerState state = [recognizer state];
    
    if (state == UIGestureRecognizerStateBegan || state == UIGestureRecognizerStateChanged)
    {
        CGFloat rotation = [recognizer rotation];
        

        [recognizer.view setTransform:CGAffineTransformRotate(recognizer.view.transform, rotation)];
        NSLog(@"rotation --%f    frame----%@",rotation,NSStringFromCGRect(recognizer.view.frame));
        [recognizer setRotation:0];
    }
}



#pragma mark ---- 发送贺卡
-(void)sendGreetCard{
    NSLog(@"send  。。。。");
    [self logEvent:@"gc_click_send"];
    
    //分享的标题
    NSString *textToShare = self.text_model.clifford_original;
    //分享的图片
    UIImage *imageToShare =     [self snapshotViewFromView:self.imagView_bg.superview];
    UIActivityViewController * shareController  = [[UIActivityViewController alloc]initWithActivityItems:@[textToShare,imageToShare] applicationActivities:nil];
    [self presentViewController:shareController animated:YES completion:nil];
    
    shareController.completionWithItemsHandler = ^(UIActivityType  _Nullable activityType, BOOL completed, NSArray * _Nullable returnedItems, NSError * _Nullable activityError) {
        if (completed) {
            NSLog(@"completed");
        } else  {
            NSLog(@"cancled");

        }
    };
    
}
#pragma mark  ---- override
-(void)onLeftButtonTouched{
    WeakSelf;
    MyAlertViewV3 * alert = [MyAlertViewV3 alertViewWithTitle:TLString(@"greeting_cards_drop_hint") block:^(NSInteger btnIdx) {
        if (btnIdx == 1)
        {
            [weakSelf logEvent:@"gc_click_yes"];
            [super onLeftButtonTouched];
        }
        else{
            [weakSelf logEvent:@"gc_click_cancle"];
        }
        
    }];
    [alert addActionWithTitle:TLString(@"Cancel") color:UIColorHex(#334139)];
    [alert addActionWithTitle:TLString(@"YES") color:UIColorHex(#00732F)];
    [alert show:NO];
    
    
}


#pragma mark ---- util method
- (CGSize)sizeWithString:(NSString*)str font:(UIFont *)font maxSize:(CGSize)maxSize
{
    NSDictionary *dict = @{NSFontAttributeName: font};
    NSStringDrawingOptions opts = NSStringDrawingUsesLineFragmentOrigin |
    NSStringDrawingUsesFontLeading;
    
    CGSize textSize = [str boundingRectWithSize:maxSize options:opts attributes:dict context:nil].size;
    return textSize;
}


/**
 添加虚线边框
 @param view 需要添加的边框的view
 */
-(void)addDotlineShapLayer:(UIView * )view{
    CAShapeLayer *borderLayer = [CAShapeLayer layer];
    borderLayer.bounds = CGRectMake(0, 0, view.width, view.height);
    borderLayer.position = CGPointMake(CGRectGetMidX(view.bounds), CGRectGetMidY(view.bounds));
    
    //    borderLayer.path = [UIBezierPath bezierPathWithRect:borderLayer.bounds].CGPath;
    borderLayer.path = [UIBezierPath bezierPathWithRoundedRect:borderLayer.bounds cornerRadius:CGRectGetWidth(borderLayer.bounds)/2].CGPath;
    borderLayer.lineWidth = 1. / [[UIScreen mainScreen] scale];
    //虚线边框
    borderLayer.lineDashPattern = @[@8, @8];
    //实线边框
    //    borderLayer.lineDashPattern = nil;
    borderLayer.fillColor = [UIColor clearColor].CGColor;
    borderLayer.strokeColor = [UIColor redColor].CGColor;
    [view.layer removeAllSublayers];
    [view.layer addSublayer:borderLayer];

}

-(UIImage *)snapshotViewFromView:(UIView *)inputView {
    UIGraphicsBeginImageContextWithOptions(inputView.bounds.size, NO, 0);
    [inputView.layer renderInContext:UIGraphicsGetCurrentContext()];
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
